package com.social.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;
import com.social.pojo.propertie.SmsProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zero
 * @version 1.0
 * @project demo
 * @description 短信工具类
 * @date 2022/12/16 12:51:21
 */
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtil {
    @Resource
    private SmsProperties smsProperties;

    public boolean send(Map<String,Object> map, String phone) {
        if(StringUtils.isEmpty(phone)) {
            return false;
        }
        DefaultProfile profile =
                DefaultProfile.getProfile(smsProperties.getEndpoint(), smsProperties.getKeyid(), smsProperties.getKeysercret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);   //手机号
        request.putQueryParameter("SignName", "阿里云短信测试");    //签名名称
        request.putQueryParameter("TemplateCode", "SMS_154950909");  //模板名称
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));  //验证码转换json数据

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
